if (not arg[3]) then
    print("usage: " .. arg[0] .. " AccountName" .. " Server " 
        .. " GuildName")
    os.exit()
end


function convertDateToMDY(date)
    daysInYear = function(y) return y % 4 == 0 and 366 or 365 end
    days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    year = 2000
    month = 1
    while date > daysInYear(year) do
        year = year + 1
        date = date - daysInYear(year)
    end
    if year % 4 == 0 then days[2] = days[2] + 1 end
    while date > days[month] do
        month = month + 1
        date = date - days[month]
    end
    return month, date, year
end
        

function printEvent(n, e)
    m, d, y = convertDateToMDY(e["mDate"])
    print([[<event>]])
    print([[<title>]] .. m .. "/" .. d .. "/" .. y ..": " .. e["mTitle"] 
            .. [[</title>]])
    if e["mDescription"] then
        print([[<summary>]] .. e["mDescription"] .. [[</summary>]])
    end
    print([[<id>]] .. e["mID"] .. "-" .. e["mDate"] .. "-" .. n .. [[</id>]])
    print([[</event>]])
end



ACCOUNT = string.upper(arg[1])
SERVER = arg[2]
GUILD = arg[3]

dofile([[/Applications/World of Warcraft/WTF/Account/]] .. ACCOUNT 
        .. [[/SavedVariables/GroupCalendar.lua]])

print([[<?xml version="1.0" encoding="utf-8"?>]])
print([[<feed xmlns="http://www.w3.org/2005/Atom">]])
print([[<title>]] .. GUILD .. [[ event calendar]] .. [[</title>]])
print([[<updated>]] .. os.date("%FT%TZ") .. [[</updated>]])

for k, v in pairs(gGroupCalendar_Database["Databases"]) do
    if string.find(string.upper(k), string.upper(SERVER)) == 1 
            and v["Guild"] 
            and string.upper(v["Guild"]) == string.upper(GUILD) then
        for _, n in pairs(v["Events"]) do
            for _, e in pairs(n) do
                printEvent(v["UserName"], e)
            end
        end
    end
end
